package cn.youwan.market.download;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import cn.youwan.market.database.MyDao;
import cn.youwan.market.entity.DownFile;
import cn.youwan.market.entity.PromotionListbean.Appbean;
import cn.youwan.market.http.YouwanSession;
import cn.youwan.market.utils.Const;
import cn.youwan.market.utils.HttpRequestUtils;
import cn.youwan.market.utils.SessionUtils;
import cn.youwan.market.utils.Utils;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.util.Log;


public class DownLoadThread extends Thread {
	DownFile file;
	public boolean flag = true;
	private int downState; // 0为等待中 1为下载中
	private Appbean bean;
	private Context context;
	private int progress;

	public DownLoadThread(Context context, Appbean bean) {
		this.context = context;
		this.bean = bean;
		initFile();
	}

	private void initFile() {
		MyDao dao = new MyDao(context);
		DownFile file = dao.queryDownApk(bean.getPkg());
		if (file != null) {
			file.saveFile = new File(Const.APKS + Utils.md5(bean.getPkg())
					+ ".apk");
			if (file.saveFile.exists()) {
				file.startPos = (int) file.saveFile.length();
				progress = file.startPos;
				Log.v("yang", file.startPos + "");
			}
			this.file = file;
		} else {
			file = new DownFile();
			File sFile = new File(Const.APKS + Utils.md5(bean.getPkg())
					+ ".apk");
			File parentFile = sFile.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			try {
				sFile.createNewFile();
				file.saveFile = sFile;
				this.file = file;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			List<NameValuePair> params=new ArrayList<NameValuePair>();
			//TODO 获得信息
//			params.add(new BasicNameValuePair("id", bean.getId()));
//			params.addAll(SessionUtils.getHeader());
			
			//String message= HttpRequestUtils.request(Const.Host + Const.DOWNLOAD, params); ??
//			String message=HttpRequestUtils.post(Const.Host + Const.DOWNLOAD, params);
//			URL url = new URL(message);
//			Log.v("yang", "下载url：" + url.toString());
			URL url = new URL(bean.getUrl());
			Log.v("TAG", url.toString());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//			for (NameValuePair nv : getHeader()) {
//				conn.setRequestProperty(nv.getName(), nv.getValue());
//			}
			conn.setRequestMethod("GET");
			RandomAccessFile accessFile = new RandomAccessFile(file.saveFile,
					"rwd");
			conn.setRequestProperty("Range", "bytes=" + file.startPos + "-");
			Log.v("TAG", "阶段1");
			if (file.fileSize == 0) {
				file.fileSize = conn.getContentLength();
			}
			accessFile.seek(file.startPos);
			InputStream is = conn.getInputStream();
			byte[] buf = new byte[1024 * 4];
			conn.connect();
			if (conn.getResponseCode() >= 400) {
				Log.v("yang", "连接出错");
			} else {
				int num;
				while ((num = is.read(buf)) != -1 && flag) {
					progress += num;
					accessFile.write(buf, 0, num);
					sendMessage();
				}
			}
			conn.disconnect();
			is.close();
			accessFile.close();
			if (flag) {
				sendSuccessMessage();
			} else {
				Log.v("yang", "取消下载");
			}
		} catch (IOException e) {
			Log.v("yang", "下载出错1");
			sendPauseMessage();
		} catch (Exception e) {
			Log.v("yang", "下载出错2");
			sendPauseMessage();
		}
	}

	private List<NameValuePair> getHeader() {
		List<NameValuePair> nvs = new ArrayList<NameValuePair>();
		YouwanSession session = YouwanSession.getYangSession(null);
		nvs.add(new BasicNameValuePair("username", session.getUserName()));
		nvs.add(new BasicNameValuePair("uid", session.getUserKey()));
		nvs.add(new BasicNameValuePair("ver", session.getVerName()));
		nvs.add(new BasicNameValuePair("model", session.getModel()));
		nvs.add(new BasicNameValuePair("os", session.getOs()));
		nvs.add(new BasicNameValuePair("imei", session.getImea()));
		nvs.add(new BasicNameValuePair("chid", session.getSource()));
		return nvs;
	}

	// 1、向详情页发送进度更新 2、向下载管理页发送进度更新 3、向列表页发送进度更新 4、向应用更新页发送更新
	private void sendMessage() {
//		if (AppDetailActivity.appDetailIntance != null
//				&& bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			AppDetailActivity.appDetailIntance.btnHandler.sendMessage(msg);
//		}
//		if (DownLoadingActivity.downLoadingIntance != null
//				&& bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			DownLoadingActivity.downLoadingIntance.btnHandler.sendMessage(msg);
//		}
//		if (PromotionActivity.PromotionIntance != null
//				&& bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			PromotionActivity.PromotionIntance.btnHandler.sendMessage(msg);
//		}
//		if (UpgradeActivity.UpgradeIntance != null && bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			UpgradeActivity.UpgradeIntance.btnHandler.sendMessage(msg);
//		}
//		if (GameCompetitiveActivity.GameComIntance != null
//				&& bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			GameCompetitiveActivity.GameComIntance.btnHandler.sendMessage(msg);
//		}
//		if (GameRankActivity.GameRankIntance != null
//				&& bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			GameRankActivity.GameRankIntance.btnHandler.sendMessage(msg);
//		}
//		if (AppCompetitiveActivity.appComIntance != null
//				&& bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			AppCompetitiveActivity.appComIntance.btnHandler.sendMessage(msg);
//		}
//		if (AppRankActivity.appRankIntance != null && bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			AppRankActivity.appRankIntance.btnHandler.sendMessage(msg);
//		}
//		if (CatoryDetailActivity.cataDetailIntance != null
//				&& bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			CatoryDetailActivity.cataDetailIntance.btnHandler.sendMessage(msg);
//		}
//		if (SpecialActivity.specialIntance != null && bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			SpecialActivity.specialIntance.btnHandler.sendMessage(msg);
//		}
//		if (SearchActivity.searchIntance != null && bean.getDownState() == 2) {
//			Message msg = new Message();
//			msg.what = 1;
//			msg.arg1 = progress;
//			msg.obj = bean.getPkg();
//			SearchActivity.searchIntance.btnHandler.sendMessage(msg);
//		}
	}

	private void sendSuccessMessage() {
		Intent intent = new Intent();
		intent.setAction(Const.DOWNLOADED_DOWNLOAD_ACTION);
		intent.putExtra("pkg", bean.getPkg());
		context.startService(intent);
	}

	// 下载出错发送暂停通知
	private void sendPauseMessage() {
		Intent intent = new Intent();
		intent.setAction(Const.PAUSE_DOWNLOAD_ACTION);
		intent.putExtra("pkg", bean.getPkg());
		context.startService(intent);
	}

	public String getPkgname() {
		return bean.getPkg();
	}

	public int getDownState() {
		return downState;
	}

	public void setDownState(int downState) {
		this.downState = downState;
	}

	public int getProgress() {
		return progress;
	}

}
